﻿using AutoMapper;
using ERPSystem.Common.Domains.Notices;
using ERPSystem.Common.Domains.PurchaseInvoiceCommon;
using ERPSystem.Common.Domains.ReturnNotice;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using SqlSugar;
using static SalesManagementWrite.API.SalesManagementWrites.ReturnNotices.ReturnNoticeCreateCommon;

namespace SalesManagementWrite.API.SalesManagementWrites.ReturnNotices
{
    public class ReturnNoticeCreateHandler: IRequestHandler<ReturnNoticeCreateCommon,Result>
    {
        private readonly ISqlSugarClient sqlSugarClient;
        private readonly IBaseRepository<refundNotice> refundNoticebaseRepository;
        private readonly IBaseRepository<refundNoticeMaterial> refundNoticeMaterialbaseRepository;
        private readonly IMapper _mapper;

        public ReturnNoticeCreateHandler(ISqlSugarClient sqlSugarClient, IBaseRepository<refundNotice> refundNoticebaseRepository, IBaseRepository<refundNoticeMaterial> refundNoticeMaterialbaseRepository, IMapper mapper)
        {
            this.sqlSugarClient = sqlSugarClient;
            this.refundNoticebaseRepository = refundNoticebaseRepository;
            this.refundNoticeMaterialbaseRepository = refundNoticeMaterialbaseRepository;
            _mapper = mapper;
        }



        /// <summary>
        /// 退货通知单添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(ReturnNoticeCreateCommon request, CancellationToken cancellationToken)
        {
            var result = new Result();
            sqlSugarClient.Ado.BeginTran();
            try
            {
                //退货通知单添加
                var reNotice = new refundNotice()
                {
                    ReturnNoticesId = request.ReturnNoticesId,
                    ThSerialnumber = request.ThSerialnumber,//流水号雪花ID
                    ReturnNumber = request.ReturnNumber,//退货单据编号
                    BusinessTypeId = request.BusinessTypeId,//业务类型
                    Warehouseld = request.Warehouseld,//仓库
                    Remark = request.Remark,//备注
                    DocumentsDate = request.DocumentsDate,//单据日期
                    Operator = request.Operator,//操作人
                    ClientName = request.ClientName,//客户名称
                    Documentstatus = request.Documentstatus,//单据状态
                    ReturnReason = request.ReturnReason,//退货原因
                    BusinessstateId = request.BusinessstateId,//业务状态
                    Processing = request.Processing,//处理方式
                };
                var purchaseInvoices = await refundNoticebaseRepository.Add(reNotice);

                //退货物料通知单批量添加
                List<refundNoticeMaterial> refundNoticeMaterials = new List<refundNoticeMaterial>();
                foreach (var item in request.refundNoticeMaterials)
                {
                    refundNoticeMaterials.Add(new refundNoticeMaterial()
                    {
                        ReturnmaterialId = item.ReturnmaterialId,
                        Documentnumber = item.DocumentNumber,//销售单号
                        Documentnumbers = item.DocumentNumbers,//发货单号
                        ItemBianma = item.ItemBianma,//物料编码
                        MaterialName = item.MaterialName,//物料名称
                        Specifications = item.Specifications,//规格
                        Measurenum = item.Measurenum,//主计量
                        ReturnShulnum = item.ReturnShulnum,// 数量
                        BeginNumbere = item.BeginNumbere,// 入库数量
                        PiHao = item.PiHao,// 批号
                        Remark = item.Remark,//备注
                        ThSerialnumber = reNotice.ThSerialnumber,//流水号外键
                    });
                }
                var purchaseInvoiceSubtableResult = await refundNoticeMaterialbaseRepository.AddRange(refundNoticeMaterials);
                if (purchaseInvoices > 0 && purchaseInvoiceSubtableResult > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                }
                sqlSugarClient.Ado.CommitTran();
                return result;
            }
            catch (Exception ex)
            {
                sqlSugarClient.Ado.RollbackTran();
                throw ex;
            }
        }
    }
}
